'use strict';
module.exports = {
	/**
	 * XXXnameXXX
	 * @url client/history/kh/churnCount 前端调用的url参数地址
	 * data 请求参数
	 * @param {String} params1  参数1
	 */
	main: async (event) => {
		let {
			data = {}, userInfo, util, filterResponse, originalParam
		} = event;
		let {
			customUtil,
			uniID,
			config,
			pubFun,
			vk,
			db,
			_
		} = util;
		// 业务逻辑开始-----------------------------------------------------------

		// 参数验证结束
		let {
			appid,
			appname,
			tv_name,
			tv_id,
			series,
			tv_image,
		} = data;
		let res = {
			code: 0,
			msg: ""
		};
		// 业务逻辑开始-----------------------------------------------------------
		// 参数验证结束
		let dbName = 'watch_records'; // 表名
		const watchRecord = await db
			.collection(dbName)
			.where({
				tv_id: tv_id,
				series: series
			})
			.get();
		// 如果不存在观看记录，则添加新记录并且观看人数累加1
		// 如果存在观看记录，则更新观看人数
		const recordId = watchRecord.data[0]._id;
		const existingUserIds = watchRecord.data[0].user_ids_loss || [];
		// Check if the current user_id already exists in the array
		const currentUserIndex = existingUserIds.indexOf(userInfo._id);
		if (currentUserIndex === -1) {
			// If the current user_id doesn't exist, add it to the array
			existingUserIds.push(userInfo._id);
			await db
				.collection(dbName)
				.doc(recordId)
				.update({
					user_ids_loss: existingUserIds,
					churnCount: db.command.inc(1)
				});
		}
		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}